<template>
  <div>
    <Card>
      <tables
        ref="tables"
        editable
        searchable
        search-place="top"
        v-model="tableData"
        :columns="columns"
        :loading="loading"
        :plusSearchColumns="plusSearchColumns"
        @on-delete="handleDelete"
        @on-batch-delete="handleBatchDelete"
        @on-refresh="getData"
        @on-select="onSelect"
        @on-search="getDataOnSearch"
        @on-select-cancel="onSelectCancel"
        @on-select-all="onSelectAll"
        @on-select-all-cancel="onSelectAllCancel"
        @on-selection-change="onSelectionChange"
        @on-sort-change="onSortChange"
        @on-filter-change="onFilterChange"
        @on-create="onCreate"
        @on-update="onUpdate"
        @on-row-click="onRowClick"
        @on-row-dblclick="onRowDblclick"
        @on-expand="onExpand"
        @on-save-edit="onSaveEdit"
        />
      <div style="float: right; margin-top:10px;">
        <Page
        :total="page.total"
        :current='page.current'
        :page-size='page.pageSize'
        :page-size-opts='page_size_opts'
        @on-page-size-change="getDataByChangeSize"
        @on-change="getData"
        show-sizer />
      </div>
      <Button style="margin: 10px 0;" type="primary" @click="exportExcel">导出为Csv文件</Button>
      <!-- 新增 -->
      <Drawer
      :title="drawerTitle"
      v-model="onCreateFlag"
      width="720"
      :mask-closable="false"
      :styles="styles"
      >
        <Form :model="formData" :label-width="100">
            <Row :gutter="32">
                <Col span="12">
                    <FormItem label="角色名称" label-position="top">
                        <Input v-model="formData.roleName" placeholder="请输入角色名称" />
                    </FormItem>
                </Col>
                <Col span="12">
                    <FormItem label="角色编码" label-position="top">
                        <Input v-model="formData.code" placeholder="请输入角色编码">
                            <!-- <span slot="prepend">http://</span> -->
                            <!-- <span slot="append">.com</span> -->
                        </Input>
                    </FormItem>
                </Col>
            </Row>
            <Row :gutter="32">
                <Col span="12">
                  <FormItem label="数据范围" label-position="top">
                    <Select
                    v-model="formData.dataScope"
                    @on-change="dataScopeChange"
                    >
                      <Option
                      v-for="dscope in dataScopeList"
                      :key="dscope.uuid"
                      :value="dscope.dictValue"
                      >{{ dscope.dictLabel }}</Option>
                    </Select>
                  </FormItem>
                </Col>
                <Col span="12" v-if="formData.dataScope == 2">
                  <FormItem label="部门" label-position="top">
                    <PickTree
                    :data="deptList"
                    :checkedMenus="selectedDeptList"
                    :labelKey="deptTreeLabelKey"
                    :valueKey="deptTreeValueKey"
                    @on-check-change='onSelectDeptChange'
                    />
                  </FormItem>
                </Col>
            </Row>
            <FormItem label="描述" label-position="top">
                <Input type="textarea" v-model="formData.description" :rows="4" placeholder="请输入个人描述" />
            </FormItem>
        </Form>
        <div class="demo-drawer-footer">
            <Button style="margin-right: 8px" @click="doCancelDraw">取消</Button>
            <Button type="primary" v-if="operation === 'create'" @click="doCreate">提交</Button>
            <Button type="primary" v-if="operation === 'edit'" @click="doUpdate">提交</Button>
        </div>
      </Drawer>
    </Card>
  </div>
</template>

<script>
import Tables from '_c/tables'
import Api from '@/api/base/role'
import DictItemApi from '@/api/base/dictItem'
import DeptApi from '@/api/base/dept'
import PickTree from './pick-tree'

export default {
  name: 'RoleTables',
  components: {
    Tables,
    PickTree
  },
  data () {
    return {
      columns: [
        { type: 'selection', width: 60, key: 'handle', align: 'center' },
        { title: '角色名称', key: 'roleName', sortable: true },
        { title: '角色编码', key: 'code', sortable: true },
        { title: '数据范围', key: 'dataScopeDictLabel' },
        // { title: '创建时间', key: 'createdTime' },
        // { title: '更新时间', key: 'updatedTime' },
        {
          title: '操作',
          key: 'handle',
          options: ['delete', 'detail'],
          button: [
            (h, params, vm) => {
              return h('Button', {
                props: {
                  type: 'text',
                  ghost: true
                },
                on: {
                  'click': () => {
                    this.onUpdate(params.row)
                  }
                }
              }, [
                h('Icon', {
                  props: {
                    type: 'md-build',
                    size: 18,
                    color: '#000000'
                  }
                })
              ])
            }
          ]
        }
      ],
      // 高级查询默认语句测试
      plusSearchColumns: [
        {
          row: 1,
          list: [
            {
              type: 'input',
              name: 'realName',
              label: '真实姓名',
              placeholder: '真实姓名',
              default: ''
            },
            {
              type: 'input',
              name: 'nickname',
              label: '昵称',
              placeholder: '昵称',
              default: ''
            },
            {
              type: 'datetime', // 时间区间，使用两个默认值, 一个默认开始时间  一个结束时间
              name: 'createdTime',
              label: '创建时间',
              placeholderStart: '开始时间',
              placeholderEnd: '结束时间',
              default: '',
              default2: ''
            }
            // {
            //   type: 'select', // 表单类型
            //   name: 'Sel', // 对应表单的字段名
            //   label: 'Sel', // 标签
            //   placeholder: '填写Sel', // 如名
            //   default: '1', // 默认值
            //   options: [
            //     {
            //       key: 'one',
            //       val: '1'
            //     },
            //     {
            //       key: 'two',
            //       val: '2'
            //     }
            //   ]
            // }
          ]
        },
        {
          row: 2,
          list: [
            {
              type: 'radio', // 多选一
              name: 'status',
              label: '启禁用',
              placeholder: '启禁用',
              default: 1,
              options: [
                {
                  key: '启用',
                  val: 1
                },
                {
                  key: '禁用',
                  val: 0
                }
              ]
            }
            // {
            //   type: 'checkbox', // 多选一
            //   name: 'checkbox',
            //   label: 'checkbox',
            //   placeholder: 'checkbox',
            //   default: ['1'],
            //   options: [
            //     {
            //       key: 'one',
            //       val: '1'
            //     },
            //     {
            //       key: 'two',
            //       val: '2'
            //     }
            //   ]
            // }
          ]
        }
      ],
      tableData: [],
      // 分页显示数组
      page_size_opts: [10, 20, 30, 50],
      page: {
        current: 1,
        pageSize: 10,
        total: 0,
        totalPage: 0
      },
      selectedRows: [],
      currentRow: {},
      showCurrentRowFlag: false,
      onCreateFlag: false,
      styles: {
        height: 'calc(100% - 55px)',
        overflow: 'auto',
        paddingBottom: '53px',
        position: 'static'
      },
      loading: false,
      drawerTitle: '',
      operation: 'create',
      formData: {
        roleName: '',
        code: '',
        roleType: '',
        userType: '',
        dataScope: '',
        description: ''
      },
      dataScopeList: [],
      deptList: [],
      deptTreeLabelKey: 'deptName',
      deptTreeValueKey: 'code',
      selectedDeptList: [],
      roleMenus: [] // 当前用户选中的菜单列表
    }
  },
  methods: {
    handleDelete (params) {
      const id = params.row.uuid
      this.loading = true
      Api.remove(id).then(res => {
        console.log(res)
        this.loading = false
      })
    },
    /**
     * 批量删除
     */
    handleBatchDelete () {
      if (this.selectedRows.length < 1) {
        console.error('至少选中一行')
        this.$Message.error('至少选中一行')
        return -1
      }
      let idList = []
      for (let i = 0; this.selectedRows.length > i; i++) {
        // 相同的去掉
        idList.push(this.selectedRows[i].uuid)
      }
      this.loading = true
      api.removeBatch(idList).then(res => {
        console.log(res)
        this.loading = false
        this.getData()
      })
      console.log(this.selectedRows)
    },
    exportExcel () {
      this.$refs.tables.exportCsv({
        filename: `table-${(new Date()).valueOf()}.csv`
      })
    },
    getData (searchObj) {
      this.loading = true
      Api.list(this.page.current, this.page.pageSize, searchObj).then(res => {
        this.arrangeDataToTable(res.data.data)
        this.loading = false
      }).catch(e => {
        console.log(e)
        this.loading = false
      })
    },
    getDataByChangeSize (index) {
      this.page.pageSize = index
      this.getData()
    },
    getDataOnSearch (searchObj) {
      this.page.current = 1
      this.getData(searchObj)
    },
    // 显示当前行数据
    showCurrentRow (row) {
      this.currentRow = row
      this.showCurrentRowFlag = true
    },
    // 单行选中
    onSelect (selection, row) {
      this.selectedRows = selection
      console.log(this.selectedRows)
    },
    onSelectCancel (selection, row) {
      this.selectedRows = selection
      console.log(this.selectedRows)
    },
    onSelectAll (selection) {
      this.selectedRows = selection
      console.log(this.selectedRows)
    },
    onSelectAllCancel (selection) {
      this.selectedRows = selection
      console.log(this.selectedRows)
    },
    onSelectionChange (selection) {
    },
    onSortChange (column, key, order) {
    },
    onFilterChange (row) {
    },
    onRowClick (row, index) {
      this.$emit('on-row-click', row, index)
    },
    onRowDblclick (row, index) {
    },
    onExpand (row, status) {
      this.$emit('on-expand', row, status)
    },
    doCancelDraw () {
      this.onCreateFlag = false
      this.resetFormData()
    },
    async onSaveEdit (params) {
      this.loading = true
      const key = params.column.key
      // Object.assign(params.row, { key : params.value})
      this.$set(params.row, key, params.value)
      await Api.update(params.row)
      // if (ret.)
      this.loading = false
    },
    onUpdate (row) {
      this.drawerTitle = '编辑'
      this.operation = 'edit'
      this.formData = row
      // 更新部门列表的选中状态
      this.updateDeptListStatus(this.deptList, this.formData.deptList)
      this.onCreateFlag = true
    },
    updateDeptListStatus (deptList, selectedDeptList) {
      if (selectedDeptList && selectedDeptList.length > 0) {
        for (let i = 0; i < deptList.length; i++) {
          const deptData = deptList[i]
          this.$set(deptData, 'checked', false)
          // deptData.checked = false
          for (let j = 0; j < selectedDeptList.length; j++) {
            const deptCode = selectedDeptList[j]
            if (deptData.code === deptCode) {
              this.$set(deptData, 'checked', true)
              // deptData.checked = true
              break
            }
          }
          if (deptData.children && deptData.children.length > 0 && selectedDeptList.length > 0) {
            this.updateDeptListStatus(deptData.children, selectedDeptList)
          }
        }
      }
    },
    doUpdate () {
      if (this.selectedDeptList.length > 0) {
        this.formData.deptList = this.selectedDeptList
      }

      Api.update(this.formData).then(res => {
        if (res.data.code === 200) {
          alert('更新成功!')
          this.resetFormData()
          this.getData()
        }
      })
    },
    onCreate () {
      this.drawerTitle = '新增'
      this.operation = 'create'
      this.onCreateFlag = true
    },
    doCreate () {
      if (this.selectedDeptList.length > 0) {
        this.formData.deptList = this.selectedDeptList
      }

      Api.add(this.formData).then(res => {
        if (res.data.code === 200) {
          alert('新增成功!')
          this.resetFormData()
          this.getData()
        }
      })
    },
    resetFormData () {
      this.formData = {
        realName: '',
        nickname: '',
        loginName: '',
        phone: '',
        email: '',
        description: ''
      }
    },
    // 装配返回数据到页面实体中
    arrangeDataToTable (data) {
      this.tableData = data.content
      this.page.current = data.pageNum
      this.page.pageSize = data.pageSize
      this.page.total = data.totalNumber
      this.page.totalPage = data.totalPage
    },
    dataScopeChange (row) {
      console.log(row)
      // row == 2 说明是自定义数据格式
      // 需要指定部门权限
    },
    onSelectDeptChange (nodes) {
      this.selectedDeptList = []
      if (nodes instanceof Array && nodes.length > 0) {
        for (let i = 0; i < nodes.length; i++) {
          const node = nodes[i]
          this.selectedDeptList.push(node.value)
        }
      }
    }
  },
  mounted () {
    Api.list().then(res => {
      this.arrangeDataToTable(res.data.data)
    })
    DictItemApi.getListByDataType('data_scope').then(res => {
      this.dataScopeList = res.data.data
    })
    DeptApi.list().then(res => {
      this.deptList = res.data.data
    })
  }
}
</script>

<style>
.demo-drawer-profile {
    font-size: 14px
}

.demo-drawer-profile .ivu-col {
    margin-bottom: 12px
}

.ivu-form-item-content {
  line-height:20px;
}

</style>
